package com.shut.vehicle.util;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 卢斌
 */
@Slf4j
public class AesBuilder {

    /**
     * AES加解密工具实例缓存
     */
    private static final ConcurrentHashMap<SecretEnum, AES> AES_CONCURRENT_HASH_MAP = new ConcurrentHashMap<>(16);

    /**
     * 固定向量
     */
    private static final byte[] IV = "0000000000000000".getBytes();


    private static AES build(SecretEnum secret) {
        return new AES(Mode.CBC, Padding.PKCS5Padding, secret.value().getBytes(StandardCharsets.UTF_8), IV);
    }


    /**
     * 懒加载获取AES对象
     *
     * @param secret    秘钥
     * @return  AES对象
     */
    public static AES get(SecretEnum secret) {
        AES aes = AES_CONCURRENT_HASH_MAP.get(secret);
        if (aes == null) {
            aes = build(secret);
            AES_CONCURRENT_HASH_MAP.putIfAbsent(secret, aes);
        }
        return aes;
    }

}
